package com.pick.base.config;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 性能监控配置
 */
@Configuration
public class PerformanceConfig {

    @Autowired
    private MeterRegistry meterRegistry;

    /**
     * HTTP请求性能监控过滤器
     */
    @Bean
    public OncePerRequestFilter performanceMonitorFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, 
                                          HttpServletResponse response, 
                                          FilterChain filterChain) throws ServletException, IOException {
                
                String uri = request.getRequestURI();
                String method = request.getMethod();
                
                Timer.Sample sample = Timer.start(meterRegistry);
                
                try {
                    filterChain.doFilter(request, response);
                } finally {
                    sample.stop(Timer.builder("http.requests")
                            .tag("method", method)
                            .tag("uri", uri)
                            .tag("status", String.valueOf(response.getStatus()))
                            .register(meterRegistry));
                }
            }
        };
    }
}